package com.translate.web.service.impl;

import com.translate.web.constant.RedisConstant;
import com.translate.web.dao.ContractMapper;
import com.translate.entity.Contract;
import com.translate.entity.Order;
import com.translate.web.service.IContractService;
import com.basic.service.impl.BaseServiceImpl;

import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

@Service
public class ContractServiceImpl extends BaseServiceImpl<Contract> implements IContractService {

	private RedisTemplate<String, Contract> redisTemplate;

	@Autowired
	public RedisTemplate<String, Contract> getRedisTemplate() {
		return redisTemplate;
	}

	public void setRedisTemplate(RedisTemplate<String, Contract> redisTemplate) {
		this.redisTemplate = redisTemplate;
	}

	protected int getId(Contract data) {
		return data.getId();
	}

	public ContractServiceImpl(ContractMapper mapper) {
		super(mapper);
	}

	protected void insertPropteris(Contract data) {
		long time = System.currentTimeMillis() / 1000;
		data.setCreateTime(time);
		data.setUpdateTime(time);
	}

	protected void updatePropteris(Contract data) {
		data.setUpdateTime(System.currentTimeMillis() / 1000);
	}

	protected Class<Contract> getEntityClass() {
		return Contract.class;
	}

	@Override
	public Contract orderToCache(int id) {

		String key = RedisConstant.getContractKey(id);

		ValueOperations<String, Contract> valueOperations = this.redisTemplate.opsForValue();

		Contract order = valueOperations.get(key);

		if (null != order) {
			return order;
		}

		order = this.getBaseMapper().selectByPrimaryKey(id);

		if (null == order) {
			order = new Contract();

			valueOperations.set(key, order, 3, TimeUnit.SECONDS);

			return order;
		}

		valueOperations.set(key, order, 13, TimeUnit.SECONDS);

		return order;

	}
}